import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken } from '@/utils/auth'
import qs from 'querystring'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API || 'http://101.37.38.67:7001',
  timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    console.log(`[请求发送] ${config.method.toUpperCase()} ${config.url}`, config.params || config.data)
    
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    console.error('请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    console.log(`[响应接收] ${response.config.url}`, response.data)
    
    const res = response.data
    if (res.status !== 200) {
      if (res.status === 500) {
        Message({ message: res.message || '服务器内部错误', type: 'error', duration: 5 * 1000 })
      }
      if (res.status === 401) {
        Message({ message: '登录已过期，请重新登录', type: 'warning', duration: 5 * 1000 })
        logout()
      }
      return Promise.reject(new Error(res.message || 'Error'))
    }
    return res
  },
  error => {
    const { config, code, message, response } = error
    
    // 获取请求URL，去除baseURL部分
    const baseURL = service.defaults.baseURL
    const url = config ? (config.url || '').replace(baseURL, '') : ''
    
    let errMsg = '未知错误'
    let status = 0
    
    if (code === 'ECONNABORTED' || message.indexOf('timeout') !== -1) {
      errMsg = '请求超时，请稍后重试'
    } else if (response) {
      status = response.status
      switch (status) {
        case 400:
          errMsg = '请求参数错误'
          break
        case 401:
          errMsg = '登录已过期，请重新登录'
          logout()
          break
        case 403:
          errMsg = '没有权限访问该资源'
          break
        case 404:
          errMsg = `请求的资源不存在: ${url}`
          break
        case 500:
          errMsg = '服务器内部错误'
          break
        default:
          errMsg = `请求失败(${status})`
      }
    } else if (message.indexOf('Network Error') !== -1) {
      errMsg = '网络连接错误，请检查网络'
    }
    
    console.error(`[请求失败] ${url}`, {
      url,
      status,
      message: errMsg,
      params: config ? (config.params || config.data) : {},
      error
    })
    
    Message({
      message: errMsg,
      type: 'error',
      duration: 5 * 1000
    })
    
    // 使用延迟Promise.reject，避免太多错误消息同时显示
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        reject(error)
      }, 300)
    })
  }
)

// 封装GET请求
export function get(url, params) {
  return service({
    url,
    method: 'get',
    params,
    headers: {
      'X-Requested-With': 'XMLHttpRequest'
    }
  })
}

// 封装DELETE请求
export function del(url, params) {
  return service({
    url,
    method: 'delete',
    params,
    headers: {
      'X-Requested-With': 'XMLHttpRequest'
    }
  })
}

// 封装POST请求（表单格式）
export function post(url, data) {
  return service({
    url,
    method: 'post',
    data: qs.stringify(data),
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
  })
}

// 封装POST请求（JSON格式）
export function postJSON(url, data) {
  return service({
    url,
    method: 'post',
    data,
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/json'
    }
  })
}

// 封装PUT请求（表单格式）
export function put(url, data) {
  return service({
    url,
    method: 'put',
    data: qs.stringify(data),
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
  })
}

// 封装PUT请求（JSON格式）
export function putJSON(url, data) {
  return service({
    url,
    method: 'put',
    data,
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/json'
    }
  })
}

// 退出登录
async function logout() {
  await store.dispatch('user/logout')
  router.push('/login')
}

export default service